import {
  searchFood,
  getFoodDetail,
  getFoodCategories,
  getCategoryFoods,
  addFavoriteFood,
  removeFavoriteFood,
  clearSearchHistory
} from '@/api/food'

export default {
  namespaced: true,

  state: {
    searchResults: [],
    foodDetail: null,
    categories: [],
    categoryFoods: [],
    recommendedFoods: [],
    loading: false,
    total: 0,
    selectedFoods: []
  },

  mutations: {
    SET_SEARCH_RESULTS(state, { list, total }) {
      state.searchResults = list
      state.total = total
    },
    SET_FOOD_DETAIL(state, detail) {
      state.foodDetail = detail
    },
    SET_CATEGORIES(state, categories) {
      state.categories = categories
    },
    SET_CATEGORY_FOODS(state, foods) {
      state.categoryFoods = foods
    },
    SET_RECOMMENDED_FOODS(state, foods) {
      state.recommendedFoods = foods
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    UPDATE_FAVORITE_STATUS(state, { foodId, isFavorite }) {
      const updateFood = (food) => {
        if (food.id === foodId) {
          food.isFavorite = isFavorite
        }
      }
      state.searchResults.forEach(updateFood)
      state.categoryFoods.forEach(updateFood)
      state.recommendedFoods.forEach(updateFood)
      if (state.foodDetail?.id === foodId) {
        state.foodDetail.isFavorite = isFavorite
      }
    },
    ADD_SELECTED_FOOD(state, food) {
      if (!state.selectedFoods) {
        state.selectedFoods = []
      }
      if (!state.selectedFoods.find(f => f.id === food.id)) {
        state.selectedFoods.push(food)
      }
    },
    REMOVE_SELECTED_FOOD(state, foodId) {
      if (state.selectedFoods) {
        state.selectedFoods = state.selectedFoods.filter(f => f.id !== foodId)
      }
    }
  },

  actions: {
    // 搜索食物
    async searchFood({ commit }, params) {
      try {
        commit('SET_LOADING', true)
        const res = await searchFood(params)
        commit('SET_SEARCH_RESULTS', res.data)
        return res
      } catch (error) {
        console.error('搜索食物失败:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 获取食物详情
    async getFoodDetail({ commit }, id) {
      try {
        const res = await getFoodDetail(id)
        commit('SET_FOOD_DETAIL', res.data)
        return res
      } catch (error) {
        console.error('获取食物详情失败:', error)
        throw error
      }
    },

    // 获取食物分类
    async getFoodCategories({ commit }) {
      try {
        const res = await getFoodCategories()
        commit('SET_CATEGORIES', res.data)
        return res
      } catch (error) {
        console.error('获取食物分类失败:', error)
        throw error
      }
    },

    // 获取分类下的食物
    async getCategoryFoods({ commit }, category) {
      try {
        commit('SET_LOADING', true)
        const res = await getCategoryFoods(category)
        commit('SET_CATEGORY_FOODS', res.data)
        return res
      } catch (error) {
        console.error('获取分类食物失败:', error)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 获取推荐食物
    async getRecommendedFoods({ commit }, type = '') {
      try {
        commit('SET_LOADING', true)
        let params = {}
        if (type) {
          params.type = type
        }
        const res = await searchFood(params)

        if (res.code === 200 && res.data) {
          commit('SET_RECOMMENDED_FOODS', res.data)
          return res.data
        }
        throw new Error(res.message || '获取推荐食物失败')
      } catch (error) {
        console.error('获取推荐食物失败:', error)
        commit('SET_RECOMMENDED_FOODS', [])
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 收藏/取消收藏食物
    async toggleFavorite({ commit }, { foodId, isFavorite }) {
      try {
        if (isFavorite) {
          await addFavoriteFood(foodId)
        } else {
          await removeFavoriteFood(foodId)
        }
        commit('UPDATE_FAVORITE_STATUS', { foodId, isFavorite })
      } catch (error) {
        console.error('操作收藏失败:', error)
        throw error
      }
    },

    // 清除搜索历史
    async clearSearchHistory({ commit }) {
      try {
        await clearSearchHistory()
        commit('SET_SEARCH_HISTORY', [])
      } catch (error) {
        console.error('清除搜索历史失败:', error)
        throw error
      }
    }
  }
} 